<template>
    <div class="map-container">
      <div id="shipPositionMap" ref="mapRef" :style="{ width: '100%', minHeight: '400px' }"></div>
    </div>
</template>

<script setup lang='ts'>
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue';
import * as echarts from 'echarts';
import service from '@/utils/request';
import useDataMapStore from '@/store/modules/dataMap';

// 引入完整的世界国家地图数据（GeoJSON格式）
import worldMapData from './countries.geo.json';

const mapRef = ref<HTMLElement | null>(null);
let myChart: echarts.ECharts | null = null;
let resizeHandler: () => void;

// 模拟船舶位置数据
const getMockShipPositions = () => {
  // 从世界主要港口随机选择一些点作为模拟数据
  const positions = [
    { name: '上海', value: [121.47, 31.23], shipName: 'MV AICC SHANGHAI', voyageNo: 'V001' },
    { name: '新加坡', value: [103.82, 1.35], shipName: 'MV AICC SINGAPORE', voyageNo: 'V002' },
    { name: '鹿特丹', value: [4.47, 51.92], shipName: 'MV AICC ROTTERDAM', voyageNo: 'V003' },
    { name: '洛杉矶', value: [-118.24, 34.05], shipName: 'MV AICC LOSANGELES', voyageNo: 'V004' },
    { name: '悉尼', value: [151.21, -33.87], shipName: 'MV AICC SYDNEY', voyageNo: 'V005' },
    { name: '迪拜', value: [55.31, 25.27], shipName: 'MV AICC DUBAI', voyageNo: 'V006' },
    { name: '汉堡', value: [9.99, 53.55], shipName: 'MV AICC HAMBURG', voyageNo: 'V007' },
    { name: '纽约', value: [-74.00, 40.71], shipName: 'MV AICC NEWYORK', voyageNo: 'V008' },
    { name: '东京', value: [139.84, 35.68], shipName: 'MV AICC TOKYO', voyageNo: 'V009' },
    { name: '孟买', value: [72.87, 19.07], shipName: 'MV AICC MUMBAI', voyageNo: 'V010' }
  ];
  return positions;
};

// 初始化世界地图
const initWorldMap = async () => {
  if (!mapRef.value) return;

  try {
    // 初始化ECharts实例
    myChart = echarts.init(mapRef.value);
    
    // 注册世界地图数据 - 使用countries.geo.json
    echarts.registerMap('world', worldMapData as any);
    
    // 获取模拟的船舶位置数据
    const shipPositions = getMockShipPositions();

    const option = {
      title: {
        text: '船舶定位',
        subtext: '当前船舶所在位置，每日模拟数据仅供参考',
        left: 'center',
        textStyle: {
          fontSize: 18,
          fontWeight: 'bold',
          color: '#333'
        },
        subtextStyle: {
          fontSize: 12,
          color: '#666'
        }
      },
      tooltip: {
        trigger: 'item',
        formatter: function(params: any) {
          if (params.seriesType === 'effectScatter') {
            return `船舶名称: ${params.data.shipName}<br/>航次号: ${params.data.voyageNo}<br/>位置: ${params.name}`;
          }
          return params.name;
        },
        backgroundColor: 'rgba(0, 0, 0, 0.7)',
        borderColor: '#409eff',
        textStyle: {
          color: '#fff'
        }
      },
      legend: {
        orient: 'vertical',
        right: 10,
        top: 'center',
        data: ['船舶位置'],
        textStyle: {
          color: '#666'
        }
      },
      geo: {
        map: 'world',
        roam: true, // 启用缩放和平移
        scaleLimit: {
          min: 1,
          max: 10
        },
        center: [0, 30], // 初始中心点位置
        zoom: 1.2, // 初始缩放级别
        label: {
          show: false, // 禁用动态显示国家名称，避免this上下文问题
          color: '#333',
          fontSize: 10,
          fontWeight: 'normal'
        },
        emphasis: {
          label: {
            show: true, // 只在悬停时显示国家名称
            color: '#fff',
            fontSize: 12,
            fontWeight: 'bold'
          },
          itemStyle: {
            areaColor: '#2a333d',
            borderWidth: 1,
            borderColor: '#409eff'
          }
        },
        itemStyle: {
          areaColor: '#f0f2f5',
          borderColor: '#dcdfe6',
          borderWidth: 0.5
        },
        silent: false // 允许鼠标事件
      },
      series: [
        {
          name: '船舶位置',
          type: 'effectScatter',
          coordinateSystem: 'geo',
          data: shipPositions,
          symbolSize: 12,
          showEffectOn: 'render',
          rippleEffect: {
            period: 3,
            scale: 3,
            brushType: 'stroke'
          },
          itemStyle: {
            color: '#409eff',
            borderWidth: 1,
            borderColor: '#fff',
            shadowBlur: 10,
            shadowColor: '#409eff'
          },
          emphasis: {
            scale: true,
            itemStyle: {
              color: '#67c23a', // 悬停时变为绿色
              shadowBlur: 20,
              shadowColor: '#67c23a'
            }
          },
          zlevel: 2
        }
      ]
    };

    myChart.setOption(option);

    // 添加地图缩放事件监听，实现缩放时动态显示国家名称
    if (myChart) {
      let currentZoom = 1.2; // 初始缩放级别
      
      myChart.on('georoam', () => {
        const option = myChart?.getOption();
        if (option && option.geo && option.geo[0]) {
          const newZoom = option.geo[0].zoom || currentZoom;
          
          // 当缩放级别大于3时显示国家名称，否则隐藏
          if (newZoom > 3 && currentZoom <= 3) {
            myChart?.setOption({
              geo: {
                label: {
                  show: true
                }
              }
            });
          } else if (newZoom <= 3 && currentZoom > 3) {
            myChart?.setOption({
              geo: {
                label: {
                  show: false
                }
              }
            });
          }
          
          currentZoom = newZoom;
        }
      });
    }

    // 添加窗口大小改变时的响应
    resizeHandler = () => {
      myChart?.resize();
    };
    window.addEventListener('resize', resizeHandler);

  } catch (error) {
    console.error('初始化世界地图失败:', error);
    // 如果地图数据加载失败，使用备用方案
    fallbackToSimpleMap();
  }
};

// 地图数据加载失败时的备用方案
const fallbackToSimpleMap = () => {
  if (!myChart) return;
  
  // 注册一个简单的世界地图轮廓
  echarts.registerMap('world', {
    type: 'FeatureCollection',
    features: []
  });
  
  const shipPositions = getMockShipPositions();
  
  myChart.setOption({
    title: {
      text: '船舶定位',
      subtext: '地图数据加载失败，显示简化版位置图',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: function(params: any) {
        return `船舶名称: ${params.data.shipName}<br/>航次号: ${params.data.voyageNo}<br/>位置: ${params.name}`;
      }
    },
    xAxis: {
      type: 'value',
      min: -180,
      max: 180,
      show: false
    },
    yAxis: {
      type: 'value',
      min: -90,
      max: 90,
      show: false
    },
    series: [
      {
        name: '船舶位置',
        type: 'scatter',
        data: shipPositions.map(pos => ({
          name: pos.name,
          value: pos.value,
          shipName: pos.shipName,
          voyageNo: pos.voyageNo
        })),
        symbolSize: 15,
        itemStyle: {
          color: '#409eff'
        },
        tooltip: {
          formatter: function(params: any) {
            return `船舶名称: ${params.data.shipName}<br/>航次号: ${params.data.voyageNo}<br/>位置: ${params.name}`;
          }
        }
      }
    ]
  });
};

// 从服务器获取真实的船舶位置数据（如果有）
const fetchRealShipPositions = async () => {
  try {
    // 这里可以根据实际情况调用后端API获取真实数据
    // const result = await service.get('/shipping/vessel/positions');
    // return result.data || [];
    return []; // 目前返回空数组，使用模拟数据
  } catch (error) {
    console.error('获取船舶位置数据失败:', error);
    return [];
  }
};

onMounted(async () => {
  try {
    // 确保船舶数据已初始化
    await useDataMapStore().initDataMap([{ key: 'vessels', api: '/shipping/vessel/list' }]);
    // 等待DOM更新
    await nextTick();
    // 初始化地图
    initWorldMap();
  } catch (error) {
    console.error('初始化组件失败:', error);
  }
});

onUnmounted(() => {
  // 清理资源
  if (resizeHandler) {
    window.removeEventListener('resize', resizeHandler);
  }
  myChart?.dispose();
  myChart = null;
});
</script>

<style lang='scss' scoped>
  .map-container {
    padding-top: 10px; 
    width: 100%;
    box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.1);
    border-radius: 4px;
    overflow: hidden;
  }
</style>